package com.wwwarehouse.usercenter.fragment.permissiondistribute;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.BaseCardDeskActivity;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CustomViewPagerInternal;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.state_layout.StateLayout;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.PopUpUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.common.tripartite_widget.viewindicator.CirclePageIndicator;
import com.wwwarehouse.usercenter.R;
import com.wwwarehouse.usercenter.adapter.SelectPermissionPagerAdapter;
import com.wwwarehouse.usercenter.bean.authoritydistribute.BatchAuthBean;
import com.wwwarehouse.usercenter.bean.authoritydistribute.CheckPermissionButton;
import com.wwwarehouse.usercenter.bean.authoritydistribute.DistributeResultBean;
import com.wwwarehouse.usercenter.bean.response.InviteInfoResponseBean;
import com.wwwarehouse.usercenter.constant.UserCenterConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

import static com.wwwarehouse.usercenter.R.id.esv_view;


/**
 * 权限管理 -> 选择你要分配的人
 * Created by ShineF on 2017/9/25 0025.
 */

public class SelectDistributionPermissionPagerFragment extends BaseFragment implements View.OnClickListener, ElasticScrollView.OnPullListener, CustomViewPagerInternal.OnPageChangeListener {

    private StateLayout mStateLayout;
    private CustomViewPagerInternal mCustomPager;
    private CirclePageIndicator mCirclePager;
    private Button mDistributeBtn;
    private RelativeLayout mRlNoData;
    private static final int SIZE = 9;
    private static final int PAGE = 1;
    private List<Fragment> mFragmentList;
    private ElasticScrollView mCustomScrollView;
    private ArrayList<InviteInfoResponseBean.InviteDetailsBean> mSelectList;
    private BatchAuthBean mDataBean;
    private InviteInfoResponseBean loadBean;
    private int mPos = 2;
    private String mSortUpDateTime = "update_time";
    private String mSortUpDateTimeDesc = "update_time desc";
    private String mSelectChooseSort = "update_time desc";
    private String mSearchRuleName = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_select_distribution_pager_permission, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mStateLayout = $(R.id.state_layout);
        mCustomPager = $(R.id.custom_pager);
        mCirclePager = $(R.id.pager_indicator);
        mDistributeBtn = $(R.id.btn_distribute);
        mCustomScrollView = $(esv_view);
        mRlNoData = $(R.id.rl_no_data);
        mCustomScrollView.setVisibility(View.INVISIBLE);
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof SelectDistributionPermissionPagerFragment) {
            mActivity.setTitle(R.string.select_distribute_permission_title);
        }
    }

    @Override
    public void requestDatas() {
        mSelectList = new ArrayList<>();
        Bundle arguments = getArguments();
        if (arguments != null) {
            mDataBean = arguments.getParcelable(UserCenterConstant.KEY_BATCH_AUTH);
        }
        mDistributeBtn.setVisibility(View.GONE);
        mDistributeBtn.setOnClickListener(this);
        mCustomScrollView.setOnPullListener(this);
        EventBus.getDefault().register(this);
        mStateLayout.showProgressView(true);
        mFragmentList = new ArrayList<>();
        requestParams(mSortUpDateTimeDesc, "");
        mStateLayout.setEmptyListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestParams(mSortUpDateTimeDesc, "");
            }
        });
        mStateLayout.setSystemListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestParams(mSortUpDateTimeDesc, "");
            }
        });
    }

    public void requestParams(String sort, String inviteName) {
        final Map<String, Object> map = new HashMap<>();
        List<String> inviteList = new ArrayList<>();
        inviteList.add("10");
        map.put("sort", sort);
        map.put("page", PAGE);
        map.put("size", SIZE);
        map.put("inviteeName", inviteName);
        map.put("inviteeMobile", "");
        map.put("inviteeList", inviteList);
        loadData(UserCenterConstant.URL_GET_INVITE_INFO, map, 1);

    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.btn_distribute) {
            showProgressDialog("正在加载");
            Map<String, Object> map = new HashMap<>();
            map.put("processId", mDataBean.authProcessUkidBean.processId);
            loadData(UserCenterConstant.CHECK_USER_IS_ON_LINE, map, 2);
        }
    }

    public void loadData(String url, Map map, int what) {
        NoHttpUtils.httpPost(url, map, new NoHttpUtils.OnResponseListener() {
            @Override
            public void onSucceed(CommonClass commonClass, int i) {
                if (1 == i) {
                    if ("0".equals(commonClass.getCode())) {
                        if (null != commonClass.getData()) {
                            mRlNoData.setVisibility(View.GONE);
                            loadBean = JSON.parseObject(commonClass.getData().toString(), InviteInfoResponseBean.class);
                            if (loadBean.getList() == null || loadBean.getList().size() == 0) {
                                mRlNoData.setVisibility(View.VISIBLE);
                            } else {
                                setData();
                            }
                        } else {
                            mStateLayout.showSystemView(commonClass.getMsg(), false);
                        }
                    }
                } else if (2 == i) {
                    if ("0".equals(commonClass.getCode())) {
                        if (null != mDataBean) {
                            Map<String, Object> map = new HashMap<>();
                            List<String> arrayList = new ArrayList<>();
                            for (InviteInfoResponseBean.InviteDetailsBean inviteDetailsBean : mSelectList) {
                                arrayList.add(inviteDetailsBean.getInviteeId());
                            }
                            map.put("businessUnitId", mDataBean.businessUnitId);
                            map.put("processUkid", mDataBean.authProcessUkidBean.processId);
                            map.put("selectedUserIds", arrayList);
                            map.put("userId", "");
                            loadData(UserCenterConstant.GET_MAIL_LIST_PERMISSION, map, 3);
                        }
                    } else {
                        mStateLayout.showSystemView(commonClass.getMsg(), false);
                    }
                } else if (3 == i) {
                    if (commonClass.getCode().equals("0")) {
                        DistributeResultBean bean = JSON.parseObject(commonClass.getData().toString(), DistributeResultBean.class);
                        if (null != bean) {
                            int status = bean.getStatus();
                            // 0->成功, 1->失败, 2->部分失败, 3->异常
                            if (status == 0) {
                                PermissionDistributeSuccessFragment fragment = new PermissionDistributeSuccessFragment();
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("resultBean", bean);
                                bundle.putString("type", "distribution");
                                fragment.setArguments(bundle);
                                pushFragment(fragment);
                            } else if (status == 1) {
                                PermissionDistributeAllErrorFragment fragment = new PermissionDistributeAllErrorFragment();
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("resultBean", bean);
                                bundle.putString("type", "distribution");
                                fragment.setArguments(bundle);
                                pushFragment(fragment);
                            } else if (status == 2) {
                                PermissionDistributeAnySuccessFragment fragment = new PermissionDistributeAnySuccessFragment();
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("resultBean", bean);
                                bundle.putString("type", "distribution");
                                fragment.setArguments(bundle);
                                pushFragment(fragment);
                            } else if (status == 3) {
                                PermissionAddressNotFoundFragment fragment = new PermissionAddressNotFoundFragment();
                                Bundle bundle = new Bundle();
                                bundle.putString("type", "distribution");
                                fragment.setArguments(bundle);
                                pushFragment(fragment);
                            }
                        }
                    } else {
                        ToastUtils.showToast(commonClass.getMsg());
                    }
                }


            }

            @Override
            public void onFailed(String s, int i) {

            }

            @Override
            public void onFinish(int i) {
                if (1 == i || 3 == i) {
                    dismissProgressDialog();
                }
            }
        }, what);
    }


    public void setData() {
        mFragmentList.clear();
        if (null != loadBean) {
            int total = loadBean.getTotal();
            int page = total % 9 == 0 ? total / 9 : (total / 9 + 1);
            for (int i = 0; i < page; i++) {
                SelectDistributionPermissionPagerContentFragment fragment = new SelectDistributionPermissionPagerContentFragment();
                Bundle bundle = new Bundle();
                bundle.putInt("page", i + 1);
                bundle.putSerializable("data", loadBean);
                fragment.setArguments(bundle);
                mFragmentList.add(fragment);
            }
            if (isAdded()) {
                SelectPermissionPagerAdapter adapter = new SelectPermissionPagerAdapter(getChildFragmentManager(), mFragmentList);
                mCustomPager.setAdapter(adapter);
                mCirclePager.setViewPager(mCustomPager);
                mCustomPager.setOffscreenPageLimit(5);
                mStateLayout.showContentView();
            }
            mCustomScrollView.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void searchOnRealTimeClick(String text) {
        if (peekFragment() instanceof SelectDistributionPermissionPagerFragment) {
            String searchRuleName;
            if (TextUtils.isEmpty(text)) {
                mSearchRuleName = "";
            } else {
                mSearchRuleName = text;
            }
            if (mSelectList.size() > 0) {
                mSelectList.clear();
                checkSelect();
            }
            requestParams(mSelectChooseSort, mSearchRuleName);
        }
    }

    @Override
    public void sortClick(View anchor) {
        showPopupWindow(anchor, mPos);
    }

    public void showPopupWindow(View anchor, int pos) {
        PopUpUtils.showBubbleInviteSort(mActivity, anchor, pos, new PopUpUtils.OnChoiceListener() {
            @Override
            public void onChoice(int position) {
                SelectDistributionPermissionPagerFragment.this.mPos = position;
                switch (position) {
                    case 2://由
                        showProgressDialog("正在排序");
                        mSelectChooseSort = mSortUpDateTimeDesc;
                        if (TextUtils.isEmpty(mSearchRuleName)) {
                            requestParams(mSortUpDateTimeDesc, "");
                        } else {
                            requestParams(mSortUpDateTimeDesc, mSearchRuleName);
                        }
                        break;
                    case 3:
                        showProgressDialog("正在排序");
                        mSelectChooseSort = mSortUpDateTime;
                        if (TextUtils.isEmpty(mSearchRuleName)) {
                            requestParams(mSortUpDateTime, "");
                        } else {
                            requestParams(mSortUpDateTime, mSearchRuleName);
                        }
                        break;
                    default:
                        break;
                }
            }
        }, null, getString(R.string.sort_type_01), getString(R.string.sort_type_02));
    }


    public void onEventMainThread(CheckPermissionButton check) {
        if (check.getType().equals("isSelect") && peekFragment() instanceof SelectDistributionPermissionPagerFragment) {
            InviteInfoResponseBean.InviteDetailsBean data = check.getData();
            if (mSelectList.contains(data)) {
                mSelectList.remove(data);
            } else {
                mSelectList.add(data);
            }
            checkSelect();
        }
    }

    @Override
    public void onDownPull() {
        ((BaseCardDeskActivity) mActivity).downPull_4();
    }

    @Override
    public void onUpPull() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPageScrolled(int i, float v, int i1) {

    }

    @Override
    public void onPageSelected(int i) {

    }

    @Override
    public void onPageScrollStateChanged(int i) {

    }

    public void checkSelect() {
        int i = 0;
        for (InviteInfoResponseBean.InviteDetailsBean bean : mSelectList) {
            if (bean.isSelect()) {
                i++;
            }
        }
        if (i != 0) {
            mDistributeBtn.setVisibility(View.VISIBLE);
        } else {
            mDistributeBtn.setVisibility(View.GONE);
        }
    }
}
